<template>
  <div class="cart">
    <!--  -->

    <van-nav-bar
      title="购物车"
      left-text="返回"
      left-arrow
      @click-left="onClickLeft"
    />
    <!-- 购物车为空时的图片 -->
    <div v-show="cart.length == 0 ? true : false">
      <img src="../assets/cartnull.png" alt="" />
      <h5 class="tips">空空如也，去首页看看吧~</h5>
    </div>
    <van-swipe-cell v-for="item in cart" :key="item.id">
      <van-card
        :num="item.amount"
        :price="item.price.toFixed(2)"
        :title="item.product.name"
        :thumb="item.product.coverImage | dalImg"
      >
        <template #tag>
          <van-checkbox v-model="item.chk" class="check" />
        </template>
        <template #footer>
          <van-stepper
            v-model="item.amount"
            class="check"
            theme="round"
            button-size="22"
            @plus="addToCart(item, 1)"
            @minus="addToCart(item, -1)"
          />
          <!--    -->
        </template>
      </van-card>
      <template #right>
        <van-button
          square
          @click="del(item.id)"
          text="删除"
          type="danger"
          class="delete-button"
        />
      </template>
    </van-swipe-cell>
    <van-submit-bar
      :price="sumprice"
      button-text="提交订单"
      :disabled="changDisabled"
      @submit="onSubmit(cart)"
    >
      <van-checkbox v-model="checkAll">全选</van-checkbox>
      <template #tip>
        <span
          @click="onClickEditAddress"
          style="color: deeppink; margin-right: 10px"
          v-show="receiver ? false : true"
          >添加收货地址</span
        >
        <span
          @click="onClickEditAddress"
          style="color: blue"
          v-show="receiver ? true : false"
          >修改收货地址</span
        >
      </template>
    </van-submit-bar>
  </div>
</template>

<script>
import { mapState } from "vuex";
import { Toast } from "vant";
import { addCartAPI, loadCartDataAPI, delCartDataAPI } from "../services/Cart";
import { submitOrderAPI } from "@/services/Orders";

export default {
  data() {
    return {
      isShow: false,
      checked: true,
      amout: 1,
      cart: [],
      // 过滤选中的数组
      productsChk: [],
      // 提交订单的参数接口的数组
      dingdan: [],
    };
  },
  async created() {
    // 加载购物车数据
    this.loadcartdata();
  },

  computed: {
    ...mapState(["receiver", "address"]),
    // 全选反选
    checkAll: {
      set(v) {
        this.cart.forEach((item) => (item.chk = v));
      },
      get() {
        return this.cart.length > 0
          ? this.cart.every((item) => item.chk)
          : false;
      },
    },
    // 价格
    sumprice() {
      return (
        this.cart
          .filter((item) => item.chk)
          .reduce((pre, cur) => pre + cur.amount * cur.price, 0) * 100
      );
    },
    // 提交按钮状态
    changDisabled() {
      return !this.cart.filter((item) => item.chk).length;
    },
  },

  methods: {
    // 加载购物车数据
    async loadcartdata() {
      const res = await loadCartDataAPI();
      // console.log(res);
      this.cart = res.data
        .filter((item) => item.product)
        .map((item) => ({ ...item, chk: false }));
    },
    // 提交订单
    async onSubmit(data) {
      this.productsChk = data
        .filter((item) => item.chk)
        .forEach((item) => {
          this.dingdan.push({ product: item.product.id, amount: item.amount });
        });
      // 如果存在收货地
      if (this.receiver && this.address) {
        const res = await submitOrderAPI({
          products: this.dingdan,
          receiver: this.receiver,
          address: this.address,
        });
        // console.log(res);
        if (res.code == 1) {
          Toast.success(res.msg);
        }
        this.loadcartdata();
        this.$eventBus.$emit("cartnum");
        this.$router.push({
          name: "UserOrders",
        });
      } else {
        Toast.fail("请先填写收货人及地址");
      }
    },
    // 返回按钮
    onClickLeft() {
      this.$router.replace({
        name: "Home",
      });
    },
    // 商品数量
    async addToCart(item, amount) {
      await addCartAPI({
        product: item.product.id,
        amount,
        price: item.product.price,
      });
    },
    // 根据Id删除一条数据
    async del(id) {
      await delCartDataAPI(id);
      this.cart.splice(
        this.cart.findIndex((item) => item.id === id),
        1
      );
      this.$eventBus.$emit("cartnum");
    },
    // 添加收货地址
    onClickEditAddress() {
      this.$router.push({
        name: "Address",
      });
    },
  },
};
</script>

<style>
.check {
  margin-top: 30px;
}
.delete-button {
  height: 100%;
}
.model {
  width: 80%;
  height: 30%;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  margin: auto;
  background-color: rgb(250, 245, 245);
  border-radius: 8px;
  box-shadow: 1px 1px 5px #aaa;
  z-index: 1212;
}
.model input {
  border-radius: 5px;
  border: none;
  height: 35px;
  margin-left: 10px;
  margin-top: 20px;
}
.model span {
  margin-left: 20px;
  /* color: white; */
}
button {
  border: none;
  width: 80px;
  height: 50px;
  background-color: rgba(135, 207, 235, 0.753);
  border-radius: 5px;
  margin-top: 20px;
  margin-left: 110px;
}
.tips {
  text-align: center;
  color: rgb(254, 90, 8, 0.8);
}
</style>
